package com.koron.housing.info.bean.dto;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.koron.housing.info.bean.po.HousingInfo;
import com.koron.housing.info.bean.po.HousingRecord;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author jzp
 * @since 2022/2/25
 */
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "房源台账详情页信息", description = "HousingInfoDTO")
public class HousingInfoDTO extends HousingInfo {

    @Setter
    @ApiModelProperty("租住记录")
    private List<HousingRecord> records;

    @ExcelProperty(value = "当前租户", index = 10)
    @ApiModelProperty("当前租户")
    private String currUsername;

    @DateTimeFormat("yyyy-MM-dd HH:mm")
    @ExcelProperty(value = "租赁合同开始日期", index = 11)
    @ApiModelProperty("租赁合同开始日期")
    private Date leaseStartTime;

    @DateTimeFormat("yyyy-MM-dd HH:mm")
    @ExcelProperty(value = "租赁合同结束日期", index = 12)
    @ApiModelProperty("租赁合同结束日期")
    private Date leaseEndTime;

    /**
     * 找到当前租户，使用,拼接
     * 且入住时间不为空并小于当前时间
     * 且退租时间为空或大于当前时间
     */
    public String getCurrUsername() {
        if (!CollectionUtils.isEmpty(this.records)) {
            Date currDate = new Date();
            this.currUsername = this.records.stream()
                    .filter(e -> e.getIntoDate() != null && e.getIntoDate().before(currDate))
                    .filter(e -> e.getOutDate() == null || e.getOutDate().after(currDate))
                    .map(HousingRecord::getName)
                    .collect(Collectors.joining(","));
        }
        return this.currUsername;
    }

    /**
     * 租赁合同开始日期
     * 找最迟的开始日期
     */
    public Date getLeaseStartTime() {
        if (!CollectionUtils.isEmpty(this.records)) {
            this.leaseStartTime = this.records.stream()
                    .map(HousingRecord::getLeaseStartTime)
                    .filter(Objects::nonNull)
                    .max(Comparator.comparing(Date::getTime))
                    .orElse(null);
        }
        return this.leaseStartTime;
    }

    /**
     * 租赁合同结束日期
     * 找最早的结束日期
     */
    public Date getLeaseEndTime() {
        if (!CollectionUtils.isEmpty(this.records)) {
            this.leaseEndTime = this.records.stream()
                    .map(HousingRecord::getLeaseEndTime)
                    .filter(Objects::nonNull)
                    .min(Comparator.comparing(Date::getTime))
                    .orElse(null);
        }
        return leaseEndTime;
    }
}
